//
//  UICityListViewController.m
//  WeatherCast
//
//  Created by long on 15/1/23.
//  Copyright (c) 2015年 anlong. All rights reserved.
//

#import "UICityListViewController.h"
#import "WeatherInfoItem.h"
#import "SBJson.h"
#import "AddCityViewController.h"
#import "ItemDetailViewController.h"

#define URL_GET_WEATHER @"http://api.map.baidu.com/telematics/v3/weather?location=%@&output=json&ak=vprRmjakEGo0ONk5kAVo5Gie&mcode=long.Weather"

@interface UICityListViewController ()

@end

@implementation UICityListViewController

@synthesize arrayCityList, data, arrayCitysWeather, userDefaultsString;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    NSLog(@"UICityListViewController viewDidLoad");
    
    NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
    
    if(!self.arrayCityList) {
        self.arrayCityList = [[NSMutableArray alloc]init];
        
        id list = [defaults objectForKey:@"cityList"];
        
        self.userDefaultsString = list;
        
        if (self.userDefaultsString && userDefaultsString.length > 0) {
            NSArray* array = [userDefaultsString componentsSeparatedByString:@"|"];
            [self.arrayCityList addObjectsFromArray:array];
        }
    }
    
    if(data) {
        [self.arrayCityList addObject:data];
        NSLog(@"接收到的数据:%@", data);
        [self.tableView reloadData];
    }
    [self RequestWeatherInfo:arrayCityList];
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return [self.arrayCityList count];
}

- (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    
    return 5.0f;
}

- (CGFloat) tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    
    return 3.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *result = nil;
    if ([tableView isEqual:self.tableView]) {
        static NSString *tableViewCellIdentifier = @"MyCells";//设置Cell标识
        result = [tableView dequeueReusableCellWithIdentifier:tableViewCellIdentifier];//通过标示符返回一个可重用的表视图单元格对象
        if (result == nil) {
            result = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:tableViewCellIdentifier];//初始化一个表格单元格样式和重用的标识符,并将它返回给调用者。
        }
        //indexPath.section 表示section的索引 indexPath.row表示行数的索引
        NSLog(@"indexPath section:%ld", (long)[indexPath row]);
        
        result.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        result.textLabel.text = [self.arrayCityList objectAtIndex:[indexPath row]];
        
        result.textLabel.font = [UIFont boldSystemFontOfSize:20.0f];
        
        result.textLabel.backgroundColor=[UIColor clearColor];
        
        if ( arrayCitysWeather ) {
            for (NSInteger i = 0; i < [arrayCitysWeather count]; i ++ ) {
                
                WeatherInfoItem* infos = [arrayCitysWeather objectAtIndex:i];
                
                if( 0 == [[self.arrayCityList objectAtIndex:[indexPath row]] compare: infos.itemName] ){
                    
                    if( [infos.itemWeatherInfo count] > 0 ){
                        WeatherData* data = [infos.itemWeatherInfo objectAtIndex:0];
                        NSString* brief = [[NSString alloc] initWithFormat:@"%@ %@ %@", data.weather, data.wind, data.temperature];
                        result.detailTextLabel.text = brief;
                    }
                }
            }
        }
    }
    
    return result;
}


//点击某一行时候触发的事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
    
    if ([tableView isEqual:self.tableView]) {
        
        NSInteger row = [indexPath row];
        
        ItemDetailViewController* itemDetailViewController = [[ItemDetailViewController alloc] init];
        
        itemDetailViewController.currentCityName = [arrayCityList objectAtIndex:row];
        
        itemDetailViewController.weatherInfoData = [self FindInfoByItemName: itemDetailViewController.currentCityName];
        
        [self.navigationController pushViewController:itemDetailViewController animated:YES];
    }
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        //        获取选中删除行索引值
        NSInteger row = [indexPath row];
        //        通过获取的索引值删除数组中的值
        [self.arrayCityList removeObjectAtIndex:row];
        //        删除单元格的某一行时，在用动画效果实现删除过程
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
    }
}


// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
    
}

//设置每行的高度
-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPat
{
    return 80.0f;
}

-(void)RequestWeatherInfo:(NSArray*)citysName
{
    NSString* strCitys = [[NSString alloc]init];
    for ( NSInteger i = 0; i < [citysName count]; i ++ ) {
        strCitys = [strCitys  stringByAppendingString: [citysName objectAtIndex:i]];
        if( i < ([citysName count] - 1 )){
            strCitys = [strCitys  stringByAppendingString: @"|"];
        }
    }
    
    NSLog(@"搜索的城市：[%@]", strCitys);
    // 北京
    
    NSString * strUrl = [NSString stringWithFormat:URL_GET_WEATHER, strCitys ];
    
    NSString * newUrl = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString : newUrl];
    
    NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    //获取一个主队列
    NSOperationQueue *queue=[NSOperationQueue mainQueue];
    
    [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError){
        NSError* error = nil;
        if(data){
            NSLog(@"%@", [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
            // find whose data
            NSMutableArray* array;
            
            [self parseWeatherJson:data outputInfo:&array error:&error];
            
            arrayCitysWeather = array;
            //
            [self.tableView reloadData];
        }
    }];
}


-(void) parseWeatherJson:(NSData*)data outputInfo:(NSMutableArray**) arrayCitysInfo error:(NSError**) error{
    
    *arrayCitysInfo = [[NSMutableArray alloc]init];
    
    NSString* jsonString = [[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
    
    SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
    
    id jsonObjects = [jsonParser objectWithString:jsonString];
    
    if ([jsonObjects isKindOfClass:[NSDictionary class]]){
        NSDictionary *rootDic = [jsonParser objectWithString:jsonString error:error];
        
        id reqError= [rootDic objectForKey:@"error"];
        //        if( [reqError isEqual:0] == NO ){
        //
        //            // TODO notify ui
        //            return;
        //        }
        
        NSArray* reslutArray = [rootDic objectForKey:@"results"];
        NSDictionary *infoDic =  nil;
        
        for (NSUInteger i = 0; i < [reslutArray count]; i ++) {
            
            WeatherInfoItem* weatherInfo = [[WeatherInfoItem alloc]init];
            weatherInfo.itemWeatherInfo = [[NSMutableArray alloc]init];
            
            infoDic = [reslutArray objectAtIndex:i];
            
            weatherInfo.itemName = [[NSString alloc]initWithFormat:@"%@", [infoDic objectForKey:@"currentCity"]];
            weatherInfo.itemPM25 = [[NSString alloc]initWithFormat:@"%@",[infoDic objectForKey:@"pm25"]];
            
            NSArray* arrayWeather_data = [infoDic objectForKey:@"weather_data"];
            
            for (NSInteger j = 0;  j < [arrayWeather_data count]; j ++ ) {
                
                NSDictionary* weather = [arrayWeather_data objectAtIndex:j];
                WeatherData* data = [[WeatherData alloc]init];
                
                data.date = [[NSString alloc]initWithFormat:@"%@", [weather objectForKey:@"date"]];
                data.weather = [[NSString alloc]initWithFormat:@"%@", [weather objectForKey:@"weather"]];
                data.wind = [[NSString alloc]initWithFormat:@"%@", [weather objectForKey:@"wind"]];
                data.temperature = [[NSString alloc]initWithFormat:@"%@", [weather objectForKey:@"temperature"]];
                
                [ weatherInfo.itemWeatherInfo addObject:data ];
            }
            
            [*arrayCitysInfo addObject:weatherInfo];
        }
    }
    else{
        
    }
}

//下载开始函下

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse*)response{
    
}

//下载中的函数

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    NSLog(@"%s",__FUNCTION__);
}

//完成加载的函数

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

}

- (IBAction)unwindToList:(UIStoryboardSegue *)segue
{
    AddCityViewController *source = [segue sourceViewController];
    NSString *item = source.cityName;
    if (item != nil) {
        [self.arrayCityList addObject:item];
        
        [self RequestWeatherInfo:self.arrayCityList];
        
        NSString* strTemp = [NSString stringWithFormat:@"%@|%@", self.userDefaultsString, item];
        
        [[NSUserDefaults standardUserDefaults] setObject:strTemp forKey:@"cityList"];
        
        self.userDefaultsString = strTemp;
        
        [self.tableView reloadData];
    }
}

-(IBAction)clickEditCityButton
{
    NSLog(@"clickEditCityButton");
    if( NO == [self.tableView isEditing] ){
        [self.tableView setEditing:YES animated:YES];
    }else{
        [self.tableView setEditing:NO animated:YES];
    }
}

- (WeatherInfoItem*) FindInfoByItemName:(NSString*)cityName
{
    WeatherInfoItem* item = nil;
    for (item in self.arrayCitysWeather) {
        if(0 == [item.itemName compare:cityName]) {
            break;
        }
    }
    return item;
}

@end
